package chapter.fifth.item25;

import java.util.ArrayList;
import java.util.List;

public class ListInsteadArray {
	
	//数组结合泛型,容易出现ClassCastException
	static <E> E arrayAndGeneric(List<E> list,Function<E> f,E initVal){
		@SuppressWarnings("unchecked")
		E[] snapshot = (E[]) list.toArray();//locks list
		E result = initVal;
		for(E e:snapshot){
			result = f.apply(result, e);
		}
		return result;
		
	}
	
	//列表结合泛型
	static <E> E listAndGeneric(List<E> list,Function<E> f,E initVal){
		List<E> snapshot;
		synchronized(list){//locks list
			snapshot = new ArrayList<E>(list);
		}
		E result = initVal;
		for(E e:snapshot){
			result = f.apply(result, e);
		}
		return result;
	}
}

interface Function<T>{
	T apply(T t1,T t2);
}
